import { Component, ViewChild } from '@angular/core';

import { Storage } from '@ionic/storage';

import { DomSanitizer } from '@angular/platform-browser';

import { Events, AlertController, App, ModalController, NavController, NavParams, ActionSheetController, Content } from 'ionic-angular';

import { EmailListService } from './list.service';

import { Config } from '../../../providers/config';

import { EmailDetailPage } from '../detail/detail.component';

import { EmailSendPage } from '../send/send.component';

import _ from 'lodash';
import {EmailQueryPage} from "../query/query.component";

@Component({
  selector: 'page-email-list',
  templateUrl: './list.html',
  providers: [EmailListService]
})
export class EmailListPage {
	moa_page_name: any = "page-email-list";
  moa_page_explain: any = "";

  @ViewChild(Content) content: Content;

  // 列表数据
  listData: any = [];
  //显示标题
  title = '';

  _ = _;
  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

  listType = "";

  listTypes = [
    {
      text: "收件箱",
      listType: "IMailInbox"
    },
    {
      text: "草稿箱",
      listType: "DraftBox"
    },
    {
      text: "发件箱",
      listType: "IMOutbox"
    },
    {
      text: "废件箱",
      listType: "WasteBox"
    },
    {
      text: "待办邮件",
      listType: "IMailTask"
    },
    {
      text: "重要邮件",
      listType: "IMailImp"
    },
    {
      text: "历史邮件",
      listType: "IMailHIS"
    }];

  keyWord = null;
  //
  queryCondition = null;

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public listService: EmailListService,
    private navParams: NavParams,
    public events: Events,
    public config: Config,
    public storage: Storage,
    private sanitizer: DomSanitizer,
    public actionSheetCtrl: ActionSheetController
  ) {
    this.storage.remove("advancedQueryCondition");

    this.initQueryCondition();

    this.listType = navParams.get('listType') ? navParams.get('listType') : "IMailInbox";
    this.title = _.find(this.listTypes, { listType: this.listType }).text;

    this.moa_page_explain = this.title;

    // 初始化数据
    this.loadListData(this.pageIndex, null, null);

    this.events.unsubscribe('email-list:delete');
    // 监听是否有删除邮件操作
    this.events.subscribe('email-list:delete', (deletedId) => {
      // user and time are the same arguments passed in `events.publish(user, time)`
      console.info('---- list--email-list:delete------');
      console.info(deletedId);
      _.remove(this.listData, {
        mailbosid: deletedId
      })
    });

    this.events.unsubscribe('email-list:update');
    // 监听是否有更新邮件操作
    this.events.subscribe('email-list:update', (updatedId, item) => {
      console.info('---- list--email-list:update------');
      var index = _.findIndex(this.listData, {
        mailbosid: updatedId
      });
      this.listData[index] = item;
    });
  }

  chooseListType() {
    let bottons = [];
    let that = this;
    // 构建弹出框
    _.each(this.listTypes, function(item, index) {
      item["handler"] = function() {
        that.content.scrollTo(0, 0, 1);
        if (that.listType !== item.listType) {
          // 清空列表
          that.listData = [];
          that.listType = item.listType;
          that.title = item.text;
          that.doRefresh(null);
          that.initQueryCondition();
          that.storage.remove("advancedQueryCondition");
          console.info(that.listType);

          that.moa_page_explain = that.title;
        }
      };
      bottons.push(item);
    });
    // 加入取消按钮
    bottons.push({
      text: '取消',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    });
    console.info(bottons);
    let actionSheet = this.actionSheetCtrl.create({
      title: '',
      buttons: bottons
    });
    actionSheet.present();
  };

  /**
   * [loadListData 加载列表数据]
   * @param {[type]} page           [页码]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
  loadListData(page, infiniteScroll, refresher) {
    this.listService.getListData(page, this.listType, this.queryCondition).subscribe(data => {
      console.info(data);
      _.forEach(data, d => {
        d.bostitle = this.sanitizer.bypassSecurityTrustHtml(d.bostitle);
      });

      if (data) {
        // 如果加载第一页，则清空数据
        if (page == 1) {
          this.isLoadMore = true;
          this.listData = [];
        }
        // 把现有数据和新加载的数据合并
        this.listData = _.concat(this.listData, data);
        // 增加搜索索引
        this.pageIndex = this.pageIndex + 1;

        // 如果返回数据少于请求页数，则不再加载更多
        if (data.length < this.config.pageSize) {
          this.isLoadMore = false;
        }
      } else {
        this.listData = [];
        this.isLoadMore = false;
      }
      // complete event
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    })
  }
  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [参数]
   */
  goDetailPage(item) {
    console.info(item);
    if (this.listType === 'DraftBox') {
      this.listService.getDetailData(item.mailbosid).subscribe(data => {
        let e: any = {};
        e = data;
        e.bostitle = data.bostitle;
        e.mailbosid = data.mailbosid;
        e.content = data.content;
        e.recievelist = data.recievelist;
        e.recievname = data.recievname;
        e.otherlist = data.otherlist;
        e.othername = data.othername;
        e.secretlist = data.secretlist;
        e.secretname = data.secretname;
        e.isreceipt = data.isreceipt;
        e.urgency = data.urgency;
        e.readflag = data.readflag;
        e.status = data.status;
        e.listType = "draft";
        this.navCtrl.push(EmailSendPage, e);
      });
    } else {
      item.readflag = 1;
      this.navCtrl.push(EmailDetailPage, {
        id: item.mailbosid,
        type: this.listType
      });
    }
  }

  ionViewDidLoad() {

  }
  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.pageIndex != 1) {
      console.info("-----------infiniteScroll------------");
      console.info(infiniteScroll);
      if (this.isLoadMore) {
        this.loadListData(this.pageIndex, infiniteScroll, null);
      } else {
        infiniteScroll.complete();
      }
    } else {
      infiniteScroll.complete();
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.pageIndex = 1;
    this.isLoadMore = true;
    this.loadListData(this.pageIndex, null, refresher);
  }


  //邮件搜索
  search() {
    //console.log("##search 关键字：" + this.keyWord);
    this.content.scrollTo(0, 0, 100);
    this.pageIndex = 1;
    this.queryCondition.keyWord = this.keyWord;
    this.queryCondition.addresser_id = null;
    this.queryCondition.recipients = null;
    this.queryCondition.startDate = null;
    this.queryCondition.endDate = null;
    this.loadListData(this.pageIndex, null, null);
  }

  showAdvancedQueryModal() {
    console.log("打开Modal");
    let queryModal = this.modalCtrl.create(EmailQueryPage, {
      "listType" : this.listType
    });
    queryModal.onWillDismiss(data => {
      if (data && data != "close") {
        this.storage.get("advancedQueryCondition")
          .then(data => {
            if (data != null) {
              this.queryCondition = data;
              this.pageIndex = 1;
              this.loadListData(this.pageIndex, null, null);
            }
          });
      }
    });
    queryModal.present();
  }

  initQueryCondition() {
    this.queryCondition = {
      "keyWord" : "",
      "addresser_id" : null,
      "addresser" : null,
      "recipients_id" : null,
      "recipients" : null,
      "startDate" : null,
      "endDate" : null
    }
  }

}


